const VueTablePlugin = {
  install: (app, options) => {
    app.component("vue-table", {
      data() {
        return {
          cols: [],
        }
      },
      props: {
        rows: Array
      },
      render: function () {

        let h = Vue.h;

        let columns = this.$slots.columns();

        let cellTempls = columns.map(col => {
          let templ = col.children.cell()[0];
          templ.columnProps = col.props;
          return templ;
        });

        let rows = this.rows?.map((row, index) => h('tr', cellTempls.map(templ => {

          let props = templ.props
          let ps = {};
          for (let k in props) {

            if (props[k].__v_isRef) {
              ps[k] = Vue.ref(props[k].value)
            }
            else {
              ps[k] = props[k]
            }
          }
          return h(templ, { row: row, columnProps: templ.columnProps, rowIndex: index, cellProps: ps })
        }
        )))

        let empty = this.$slots.empty;
        if (empty) empty = h(empty()[0]);
        let footer = this.$slots.footer;
        if (footer) footer = h(footer()[0]);

        let headTds = columns.map(col => {

          let headTempl = col.children.default ? col.children.default()[0] : undefined;
          let columnProps = col.props;
          if (!headTempl) {
            return h(columnProps.title);
          }
          else {
            return h(headTempl, { columnProps: columnProps });
          }
        })
        return h('table',
          [

            h('thead', h('tr', headTds)),
            h('tbody', rows?.length > 0 ? rows : empty),
            h('tfoot', footer),

          ]);
      },

    })

    app.component("column", {
    });

    app.component("head-templ", {
      props: {
        columnProps: Object,
      },
      template: `<td>
      <slot :columnProps='columnProps'></slot>
       </td> `,

    });
    app.component("cell-templ", {
      props: {
        row: Object,
        rowIndex: Number,
        columnProps: Object,
        cellProps: Object
      },
      template: `<td>
      <slot :row='row' :rowIndex='rowIndex' :columnProps='columnProps' :cellProps='cellProps'></slot>
      </td>
        `,

    });

    app.config.globalProperties.$ref = Vue.ref;
    app.config.globalProperties.$shallowRef = Vue.shallowRef;
    app.config.unwrapInjectedRef = true;

  }
};
